package com.core.family.biz.yizhao.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.core.common.annotation.MenuDesc;
import com.core.common.domain.response.R;
import com.core.common.gen.BaseQuery;
import com.core.common.gen.PageQuery;
import com.core.common.utils.IpUtil;
import com.core.common.utils.JacksonUtil;
import com.core.common.utils.JwtUtil;
import com.core.family.admin.domain.dto.SysUserDto;
import com.core.family.admin.domain.dto.WxLoginInfo;
import com.core.family.admin.domain.po.PlatUser;
import com.core.family.admin.domain.po.User;
import com.core.family.admin.domain.req.PlatUserReq;
import com.core.family.admin.service.PlatUserService;
import com.core.family.biz.yizhao.domain.dto.YzUserDto;
import com.core.family.biz.yizhao.domain.po.YzUserExtend;
import com.core.family.biz.yizhao.service.YzUserExtendService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.ResponseUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;


/**
 * @author honglei
 * @version 1.0
 * @time: 2023-6-15 10:13:03
 * @Description 服务实现层 平台用户
 */
@Slf4j
@MenuDesc(desc = "一招用户", code = "YzUser")
@Api(tags = "YzUserController 一招用户")
@RestController
@RequestMapping("/api/YzUser/")
public class YzUserController {

    @Autowired
    PlatUserService service;

    @Autowired
    YzUserExtendService extendService;

    Map<String, String> localMap = new HashMap<>();


    @ApiOperation(value = "一招登录接口")
    @MenuDesc(desc = "一招登录")
    @PostMapping("login")
    public R login(@RequestBody PlatUser user) {
        isVcodeRight(null);
        log.info("login bean:{}", user);


        LambdaQueryWrapper<PlatUser> wrapper = new LambdaQueryWrapper<>(user);
        PlatUser dbUser = service.getOne(wrapper);
        if (Objects.isNull(dbUser)) {
            return R.error("用户不存在");
        }
        YzUserExtend extend = extendService.getById(dbUser.getId());

        YzUserDto sysUserDto = new YzUserDto();
        if (Objects.nonNull(extend)) {
            BeanUtils.copyProperties(extend, sysUserDto);
        }
        BeanUtils.copyProperties(dbUser, sysUserDto);


        String token = JwtUtil.createJwt(dbUser.getId().toString(), dbUser.getMobile(), new HashMap<>());
        Map<String, Object> adminInfo = new HashMap<>();
        adminInfo.put("nickName", sysUserDto.getUsername());
        adminInfo.put("avatar", sysUserDto.getAvatar());

        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("token", token);
        result.put("adminInfo", adminInfo);

        sysUserDto.setAdmin(false);
        if (dbUser.getUsername().equals("admin")) {
            sysUserDto.setAdmin(true);
        }
        sysUserDto.setToken(token);

        if (Objects.nonNull(user.getVcode())) {
            if (! user.getVcode().equals(getMvcode(user.getMobile()))){
                return R.error("手机号验证码不正确");
            }
            localMap.remove(user.getMobile());
        }

        return R.ok(sysUserDto);
    }


    /**
     * 根据id获取详情
     *
     * @param request
     * @param id
     * @return
     */
    @GetMapping(value = "get/{id}")
    public R get(HttpServletRequest request, @PathVariable("id") String id) {
        PlatUser dbUser = service.getById(id);
        if (Objects.isNull(dbUser)) {
            return R.error("用户不存在");
        }
        YzUserExtend extend = extendService.getById(dbUser.getId());
        YzUserDto sysUserDto = new YzUserDto();
        if (Objects.nonNull(extend)) {
            BeanUtils.copyProperties(extend, sysUserDto);
        }
        BeanUtils.copyProperties(dbUser, sysUserDto);
        return R.ok(sysUserDto);
    }


    /**
     * 分页查询
     *
     * @return
     */
    @RequestMapping(value = "getPage", method = {RequestMethod.GET, RequestMethod.POST})
    public R getPage(@RequestBody PageQuery<PlatUserReq> pageQuery) {

        PageQuery<BaseQuery> baseQuery = new PageQuery<>();
        baseQuery.setQueryBean(pageQuery.getQueryBean());
        baseQuery.setPageIndex(pageQuery.getPageIndex());
        baseQuery.setPageSize(pageQuery.getPageSize());
        return R.ok(service.selectPage(baseQuery));
    }

    /**
     * 批量查询
     *
     * @return
     */
    @RequestMapping(value = "getList", method = {RequestMethod.GET, RequestMethod.POST})
    public R getList(@RequestBody PlatUserReq queryReq) {
        return R.ok(service.selectList(queryReq));
    }


    /**
     * 新增
     *
     * @param bean
     * @return
     */
    @PostMapping(value = "save")
    public R save(@RequestBody YzUserDto bean) {
        if (Objects.isNull(bean.getIsDel())) {
            bean.setIsDel(0);
        }
        service.saveOrUpdate(bean);
        YzUserExtend extend = new YzUserExtend();
        BeanUtils.copyProperties(bean, extend);
        if (Objects.isNull(extend.getIsDel())) {
            extend.setIsDel(0);
        }
        extendService.saveOrUpdate(extend);
        return R.ok();
    }


    /**
     * 用户审核
     *
     * @param bean
     * @return
     */
    @PostMapping(value = "audit")
    public R audit(@RequestBody YzUserDto bean) {
        PlatUser dbUser = service.getById(bean.getId());


        service.updateById(bean);
        return R.ok();
    }

    /**
     * 删除
     *
     * @param request
     * @param id
     * @return
     */
    @PostMapping(value = "del/{id}")
    public R del(HttpServletRequest request, @PathVariable("id") Long id) {
        return R.ok(service.removeById(id));
    }

    /**
     * 批量删除
     *
     * @param request
     * @param ids
     * @return
     */
    @PostMapping(value = "batch/del")
    public R batchDel(HttpServletRequest request, @RequestBody List<String> ids) {
        return R.ok(service.removeByIds(ids));
    }


    /**
     * 验证码
     *
     * @param request
     * @param ids
     * @return
     */
    @GetMapping(value = "getVcode")
    public R getVcode(String mobile) {
        String vcode = getMvcode(mobile);

        // TODO: 2023/7/22 短信发送
        return R.ok(vcode);
    }


    /**
     * 绑定手机号
     *
     * @param bean
     * @return
     */
    @PostMapping(value = "saveMobile")
    public R saveMobile(@RequestBody PlatUser bean) {
        log.info("saveMobile bean:{}", bean);
        if (Objects.isNull(bean.getId()) || Objects.isNull(bean.getMobile()) || Objects.isNull(bean.getVcode())) {
            return R.error("缺少必要参数id,mobile,vcode");
        }


        if ( bean.getVcode().equals(getMvcode(bean.getMobile()))){
            service.saveOrUpdate(bean);
            localMap.remove(bean.getMobile());
            return R.ok();
        }

        return R.error("验证码不存在或已失效");
    }


    @Autowired
    private WxMaService wxService;


    /**
     * 微信登录
     *
     * @param wxLoginInfo 请求内容，{ code: xxx, userInfo: xxx }
     * @param request     请求对象
     * @return 登录结果
     */
    @PostMapping("login_by_weixin")
    public Object loginByWeixin(@RequestBody WxLoginInfo wxLoginInfo, HttpServletRequest request) {
        log.info("loginByWeixin bean:{}", wxLoginInfo);
        String code = wxLoginInfo.getCode();
        WxLoginInfo.UserInfo userInfo = wxLoginInfo.getUserInfo();
        if (code == null) {
            return null;
        }
        String sessionKey = null;
        String openId = null;
        String unionid = null;
        try {
            WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
            log.info("loginByWeixin ->result:{}", request);
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
            unionid = result.getUnionid();
        } catch (Exception e) {
            e.printStackTrace();
            //  return R.error(e.getMessage());

        }
        if (openId == null) {
            //  return R.error("获取openId失败");
            openId = "kkk";
        }
        PlatUser user = service.queryByOpenid(openId);
        if (user == null) {
            user = new PlatUser();
            user.setPassword("123456");
            user.setUsername(openId);
            user.setOpenid(openId);
            user.setAvatar("http://admin.api.moyangjia.top/static/picture/1690029531295-i14q.jpg");
            service.save(user);
        } else {
        }
        PlatUser lu = new PlatUser();
        lu.setOpenid(user.getOpenid());
        return login(user);
    }


//    /**
//     * 微信手机号码绑定
//     *
//     * @param userId
//     * @param body
//     * @return
//     */
//    @PostMapping("bindPhone")
//    public Object bindPhone( @RequestBody String body) {
//        PlatUser dbUser=null;
//        if (Objects.isNull(dbUser)){
//            return R.error("用户不存在");
//        }
//        YzUserExtend extend = extendService.getById(dbUser.getId());
//        YzUserDto sysUserDto = new YzUserDto();
//        if (Objects.nonNull(extend)){
//            BeanUtils.copyProperties(extend,sysUserDto);
//        }
//        BeanUtils.copyProperties(dbUser,sysUserDto);
//
//
//
//        String phone= JacksonUtil.parseString(body, "phone");
//        String code=JacksonUtil.parseString(body, "code");
//
//
//        /*小程序绑定*/
//        if (StringUtils.isEmpty(phone)){
//            String encryptedData = JacksonUtil.parseString(body, "encryptedData");
//            String iv = JacksonUtil.parseString(body, "iv");
//            WxMaPhoneNumberInfo phoneNumberInfo = this.wxService.getUserService().getPhoneNoInfo(user.getSessionKey(), encryptedData, iv);
//            phone = phoneNumberInfo.getPhoneNumber();
//        }
//        user.setMobile(phone);
//        if (userService.updateById(user) == 0) {
//            return ResponseUtil.updatedDataFailed();
//        }
//        return ResponseUtil.ok(user);
//    }


    private boolean isVcodeRight(String mobile) {
        List<String> delList = new ArrayList<>();
        for (String s : localMap.keySet()) {
            String st = localMap.get(s).substring(0, 14);
            if (DateUtil.parse(st).offset(DateField.MINUTE, 10).isBefore(new Date())) {
                delList.add(s);
            }
        }
        for (String s : delList) {
            localMap.remove(s);
        }
        if (Objects.nonNull(mobile)) {
            return localMap.containsKey(mobile);
        }

        return false;
    }

    private String getMvcode(String mobile) {
        if (isVcodeRight(mobile)) {
            String vcode = localMap.get(mobile).substring(15);
            return vcode;
        }
        String vcode = RandomUtil.randomNumbers(6);
        log.info("getVcode mobile:{} vcode:{}", mobile, vcode);
        String value = new DateTime().toString("yyyyMMddHHmmss") +"-"+ vcode;
        localMap.put(mobile, value);

        return vcode;
    }


}
